//
//  ViewController.m
//  timerForTestSleep
//
//  Created by  Mac on 2017/8/16.
//  Copyright © 2017年  Mac. All rights reserved.
//

#import "ViewController.h"


#import "SecondViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<AVAudioPlayerDelegate>


@property(nonatomic,strong)AVAudioPlayer * audioPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    这里代码 程序启动的时候就写 只要保障音乐持续播放，程序就不会死掉，程序中的定时器和其他代码可以长久持续执行
    
    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(dispatchQueue, ^(void) {
        
        NSError *audioSessionError = nil;
        
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        
        if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
            
            NSLog(@"Successfully set the audio session.");
            
        } else {
            
            NSLog(@"Could not set the audio session");
            
        }
        
        NSBundle *mainBundle = [NSBundle mainBundle];
        
        NSString *filePath = [mainBundle pathForResource:@"xiaoxiaoshaonian" ofType:@"mp3"];
        
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
        
        NSError *error = nil;
        
        
        
        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
        
        
        
        if (self.audioPlayer != nil){
            
            self.audioPlayer.delegate = self;
            
            [self.audioPlayer setNumberOfLoops:-1];
            
            if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
                
                NSLog(@"Successfully started playing...");
                
            } else {
                
                NSLog(@"Failed to play.");
                
            }
            
        } else {
            
            
            
        }
        
    });
    
    UIButton * button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(10, 65, 60, 30);
    button.backgroundColor = [UIColor colorWithRed:255/255.0 green:211/255.0 blue:155/255.0 alpha:1];
    button.layer.cornerRadius = 5;
    [button setTitle:@"取字" forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(getPic) forControlEvents:(UIControlEventTouchUpInside)];
    [button setTitleColor:[UIColor colorWithRed:153/255.0 green:50/255.0 blue:204/255.0 alpha:1] forState:(UIControlStateHighlighted)];
    [self.view addSubview:button];

}

-(void)getPic
{
    
    SecondViewController * vc = [[SecondViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
